package cn.swu.cs.myapplication5

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.viewpager2.adapter.FragmentStateAdapter
import androidx.viewpager2.widget.ViewPager2
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayoutMediator

class MainActivity : AppCompatActivity() {
    private lateinit var viewPager2: ViewPager2

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        viewPager2 = findViewById(R.id.viewpager)
        viewPager2.adapter = ViewPagerAdapter(this)

         val tabLayout = findViewById<TabLayout>(R.id.tabLayout)
        // 将 TabLayout 中的 Item 和 viewPager2 中的 Fragment 进行关联
        TabLayoutMediator(tabLayout, viewPager2) { tab: TabLayout.Tab, position: Int ->
            when (position) {
                0 -> {
                    // 设置 item 的文字内容与 icon
                    tab.text = getString(R.string.tab1)

                }
                1 -> {
                    tab.text = getString(R.string.tab2)

                }
                2 -> {
                    tab.text = getString(R.string.tab3)

                }
                3 -> {
                    tab.text = getString(R.string.tab4)

                }
            }
        }.attach()

    }

     private inner class ViewPagerAdapter(fa: FragmentActivity) : FragmentStateAdapter(fa) {
         private val fragmentList: List<Fragment> =
             listOf(Fragment1(), Fragment2(), Fragment3(),Fragment4())
         override fun getItemCount() = fragmentList.size
         override fun createFragment(position: Int): Fragment = fragmentList[position]

     }

}